package com.atfcm.stack;

import java.util.Deque;
import java.util.LinkedList;

public class T_394_字符串解码 {
    // abc3[cd]xyz
    // https://leetcode.cn/problems/decode-string/solutions/19447/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/
    // 评论区
    // 难
    public String decodeString(String s) {
        Deque<Integer> digStack = new LinkedList<>();
        Deque<StringBuilder> strStack = new LinkedList<>();
        int num = 0;
        StringBuilder st = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if('0' <= c && c <= '9') {
                num = num * 10 + (c - '0');
            }else if ('[' == c){
                digStack.push(num);
                strStack.push(st);
                st = new StringBuilder();
                num = 0;
            }else if(']' == c){
                Integer pop = digStack.pop();
                StringBuilder pop1 = strStack.pop();
                for (int j = 0; j < pop; j++) {
                    pop1.append(st.toString());
                }
                st = pop1;
            }else {
                st.append(c);
            }

        }
        return st.toString();
    }
}
